package models

import (
	"errors"
	//"fmt"

	"fmt"
	"log"

	//"strings"
	"time"

	//"strconv"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/validation"
	"github.com/tidwall/gjson"
)

type Xf_app struct {
	Id int64 `json:"id"	orm:"column(id);pk"`
	//Appid      string `json:"appid"	orm:"size(12)" form:"appid"`
	Appname    string `json:"appname"`
	Jrtype     string `json:"jrtype"`
	Clusterid  string `json:"clusterid"`
	Deployment string `json:"deployment"`
	Namespace  string `json:"namespace"`
	Serverip   string `json:"serverip"`
	Kibanaurl  string `json:"kibanaurl"`
	Remarks    string `json:"remarks"`
	Updatetime string `json:"updatetime"`
	Createtime string `json:"createtime"`
}

func checkXf_app(u *Xf_app) (err error) {
	valid := validation.Validation{}
	b, _ := valid.Valid(&u)
	if !b {
		for _, err := range valid.Errors {
			log.Println(err.Key, err.Message)
			return errors.New(err.Message)
		}
	}
	return nil
}

func init() {
	orm.Debug = true
	orm.RegisterModel(new(Xf_app))
}

//List
func GetXf_appList(page int64, page_size int64, id int64) (xf_app []orm.Params, count int64) {
	o := orm.NewOrm()
	slb := new(Xf_app)
	qs := o.QueryTable(slb)
	var offset int64
	if page <= 1 {
		offset = 0
	} else {
		offset = (page - 1) * page_size
	}
	if id > 0 {
		qs.Filter("id", id).Limit(page_size, offset).OrderBy("-id").Values(&xf_app)
	} else {
		qs.Limit(page_size, offset).OrderBy("-id").Values(&xf_app)
	}
	count, _ = qs.Count()
	return xf_app, count
}

//List
func GetXf_appListV2(whereMap map[string]gjson.Result) (xf_app []orm.Params, count int64) {
	o := orm.NewOrm()
	cond := orm.NewCondition()

	slb := new(Xf_app)
	qs := o.QueryTable(slb)

	//var sqlstr = "SELECT * FORM xf_app WHERE "
	//var whereStr string
	var id, page, limit int64
	if pg, ok := whereMap["page"]; ok {
		page = pg.Int()
		delete(whereMap, "page")
	}
	if pg, ok := whereMap["limit"]; ok {
		limit = pg.Int()
		delete(whereMap, "limit")
	}
	var offset int64
	if page <= 1 {
		offset = 0
	} else {
		offset = (page - 1) * limit
	}
	//存在传入独立ID,就直接查询，否则进行匹配
	if pg, ok := whereMap["id"]; ok {
		id = pg.Int()
		qs.Filter("id", id).Limit(limit, offset).OrderBy("-id").Values(&xf_app)
	} else {
		for kk, vv := range whereMap {
			if vv.String() != "" {
				cond = cond.And(kk+"__contains", vv.String())
			}
		}
		qs = qs.SetCond(cond)
		qs.Limit(limit, offset).OrderBy("-id").Values(&xf_app)
	}
	//o.Raw(sqlstr).Values(&xf_app)
	count, _ = qs.Count()
	return xf_app, count
}

//添加
func AddXf_app(u *Xf_app) (int64, error) {
	if err := checkXf_app(u); err != nil {
		return 0, err
	}
	o := orm.NewOrm()
	Xf_app := new(Xf_app)
	Xf_app.Appname = u.Appname
	Xf_app.Jrtype = u.Jrtype
	Xf_app.Clusterid = u.Clusterid
	Xf_app.Namespace = u.Namespace
	Xf_app.Deployment = u.Deployment
	Xf_app.Serverip = u.Serverip
	Xf_app.Remarks = u.Remarks
	Xf_app.Createtime = time.Now().Format("2006-01-02 15:04:05")
	Xf_app.Updatetime = time.Now().Format("2006-01-02 15:04:05")
	//fmt.Println(Xf_app)
	id, err := o.Insert(Xf_app)
	return id, err
}

//更新
func UpdateXf_app(u *Xf_app) (int64, error) {
	if err := checkXf_app(u); err != nil {
		return 0, err
	}
	o := orm.NewOrm()
	op := make(orm.Params)

	if len(u.Appname) > 0 {
		op["Appname"] = u.Appname
	}
	if len(u.Jrtype) > 0 {
		op["Jrtype"] = u.Jrtype
	}
	if len(u.Clusterid) > 0 {
		op["Clusterid"] = u.Clusterid
	}
	if len(u.Namespace) > 0 {
		op["Namespace"] = u.Namespace
	}
	if len(u.Deployment) > 0 {
		op["Deployment"] = u.Deployment
	}
	if len(u.Serverip) > 0 {
		op["Serverip"] = u.Serverip
	}
	if len(u.Remarks) > 0 {
		op["Remarks"] = u.Remarks
	}
	if len(u.Kibanaurl) > 0 {
		op["Kibanaurl"] = u.Kibanaurl
	}
	op["Updatetime"] = time.Now().Format("2006-01-02 15:04:05")
	if len(op) == 0 {
		return 0, errors.New("update field is empty")
	}

	var table Xf_app
	num, err := o.QueryTable(table).Filter("Id", u.Id).Update(op)
	return num, err
}

func DelXfappById(id int64) (int64, error) {
	o := orm.NewOrm()
	status, err := o.Delete(&Xf_app{Id: id})
	return status, err
}

func EditApp(id, key, value string) (int64, error) {
	o := orm.NewOrm()
	sqlstr := fmt.Sprintf("UPDATE xf_app SET %s = '%s' WHERE  id = %s", key, value, id)
	res, err := o.Raw(sqlstr).Exec()
	if err == nil {
		num, _ := res.RowsAffected()
		log.Printf("[INFO] EditApp affected nums:%d\n", num)
		return num, nil
	}
	return 0, err
}
